import React, { useState, useMemo, useEffect } from "react";
import type { MenuProps } from "antd";
import { Menu, Layout } from "antd";
import {
    HomeOutlined,
    DatabaseOutlined,
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
// 1- 引入侧边栏 关联的数组
import { renderMenuItem } from "@/routes";
const { Sider } = Layout;
type MenuItem = Required<MenuProps>["items"][number];

function getItem(
    label: React.ReactNode,
    key: React.Key,
    icon?: React.ReactNode,
    children?: MenuItem[],
): MenuItem {
    return {
        key,
        icon,
        children,
        label,
    } as MenuItem;
}
// const items: MenuItem[] = [
//     getItem('主页', '/', <HomeOutlined />),
//     getItem('数据管理', 'sub1', <DatabaseOutlined />, [
//         getItem('数据字典', '/cmn/dict')
//     ]),
// ];

function IndexSider() {
    const [collapsed, setCollapsed] = useState<boolean>(false);
    const navigate = useNavigate();
    const { pathname } = useLocation();

    // 2- 让路由配置数组与侧边栏进行关联
    const items: MenuItem[] = useMemo(() => {
        return renderMenuItem().map((item: any) => {
            let childrenItem;
            if (item.children) {
                childrenItem = item.children.filter((v: any) => !v.isHide).map((item: any) => {
                    return getItem(item.label, item.path);
                })
            }
            return getItem(item.label, item.path, item.icon, childrenItem);
        })
    }, []);
    // 1- 获取/下的路由path
    // console.log(pathname);
    // console.log(pathname.split('/'));   
    // console.log(pathname.split('/')[1]);
    // console.log("/" + pathname.split('/')[1]);
    const [keys, setKeys] = useState<string>("/" + pathname.split('/')[1]);
    // 2- 将获取的path作为keys状态的值
    useEffect(() => {
        setKeys("/" + pathname.split('/')[1]);
    }, [pathname])
    return (
        <Sider breakpoint={"md"} collapsible collapsed={collapsed} onCollapse={value => setCollapsed(value)}>
            <div className="logo">
                <img src={require("@/assets/img/logo.png")} alt="" />
                <span style={{ display: collapsed ? "none" : "inline-block" }}>尚医通管理系统</span>
            </div>
            <Menu onClick={({ key }) => {
                // console.log(e.key);
                navigate(key);
            }} theme="dark"
                // 当前展开的 SubMenu 菜单项 key 数组
                openKeys={[keys]}
                // 3-SubMenu 展开/关闭的回调
                onOpenChange={(openKeys: string[]) => {
                    // console.log(openKeys)
                    setKeys(openKeys[1]);
                }}
               selectedKeys={[pathname]} mode="inline" items={items}/>
        </Sider>
    )
}
export default IndexSider;
